package com.woniuxy.gateway.filter;

import com.woniuxy.core.exception.WoniuxyException;
import com.woniuxy.core.util.MyJwtUtil;
import com.woniuxy.gateway.config.UrlParseConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ObjectUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


@Component
@Order(1)
public class AuthenticationFilter implements GlobalFilter {

    @Autowired
    private UrlParseConfig upc;
    private AntPathMatcher pm = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getPath().toString();
        System.out.println(url);
        //判断需不需要公共放行
        if (isMatch(url,upc.getCommonUrl())) return chain.filter(exchange);
        List<String> tkList = exchange.getRequest().getHeaders().get("token");
        String token = null;
        if (!ObjectUtils.isEmpty(tkList)) token=tkList.get(0);
        //解析
        if (url.endsWith(".api")){//管理系统解析
            //管理系统是否放行
            if (isMatch(url,upc.getAdminUrl())) return chain.filter(exchange);
            try {
                MyJwtUtil.parseAdminToken(token);
            } catch (Exception e) {
                e.printStackTrace();
                throw new WoniuxyException(401,"登录未认证（未登录）");
            }
        } else if (url.endsWith(".venue")) {
            if (isMatch(url,upc.getVenueUrl())) return chain.filter(exchange);
            try {
                MyJwtUtil.parseVenueToken(token);
            } catch (Exception e) {
                e.printStackTrace();
                throw new WoniuxyException(401,"登录未认证（未登录）");
            }
        } else if (url.endsWith(".coach")) {
            if (isMatch(url,upc.getCoachUrl())) return chain.filter(exchange);
            try {
                MyJwtUtil.parseCoachToken(token);
            } catch (Exception e) {
                e.printStackTrace();
                throw new WoniuxyException(401,"登录未认证（未登录）");
            }
        } else {//用户系统解析
            //用户系统是否放行
            if (isMatch(url,upc.getUserUrl())) return chain.filter(exchange);
            try {
                MyJwtUtil.parseUserToken(token);
            } catch (Exception e) {
                e.printStackTrace();
                throw new WoniuxyException(401,"登录未认证（未登录）");
            }
        }
        return chain.filter(exchange);//放行
    }

//    private Mono<Void> writeResp(ServerWebExchange exchange){
//        Result<?> res = Result.fail(401, "登录未认证（未登录）");
//        String jsonStr = JSONUtil.parse(res).toString();
//        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
//        return exchange.getResponse().writeWith(Mono.fromSupplier(() -> {
//            return exchange.getResponse().bufferFactory().wrap(jsonStr.getBytes());
//        }));
//    }

    private Boolean isMatch(String path,List<String> urls){
        for (String url : urls) {
            if (pm.match(url,path)) return true;
        }
        return false;
    }


}
